package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.BankCodeInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.BankCodeInfo;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.CupsInstInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.DateUtil;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author LiuYuLiang.LL
 */
@Service
public class BankCodeInfoServiceImpl extends ServiceImpl<BankCodeInfoMapper, BankCodeInfo> implements BankCodeInfoService {
    @Autowired
    IUpmpPrivilegeCheckService privilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    private String oprMenuId = "20000011";
    private String oprMenuName = "参数管理:联行号管理";
    private String oprBtnNamePrefix = "联行号管理";
    private String webNextUrl = "/admin/merParam/bankCodeInfo/edit";

    @Override
    public IPage<BankCodeInfo> findByPage(QueryRequest request, BankCodeInfo info) {
        try {
            LambdaQueryWrapper<BankCodeInfo> queryWrapper = new LambdaQueryWrapper<>();

            if (StringUtils.isNotBlank(info.getBankBranchName())) {
                queryWrapper.like(BankCodeInfo::getBankBranchName, info.getBankBranchName());
            }
            if (StringUtils.isNotBlank(info.getBankName())) {
                queryWrapper.like(BankCodeInfo::getBankName, info.getBankName());
            }
            queryWrapper.orderByDesc(BankCodeInfo::getCreateTime);
            Page<BankCodeInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }

    /**
     * 查询单个
     */
    @Override
    public BankCodeInfo findByBankBranchCode(BankCodeInfo info) {
        LambdaQueryWrapper<BankCodeInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BankCodeInfo::getBankBranchCode, info.getBankBranchCode());
        List<BankCodeInfo> bankCodeInfos = this.baseMapper.selectList(queryWrapper);
        return bankCodeInfos.get(0);
    }

    @Override
    @Transactional
    public void create(BankCodeInfo entity) throws RedpException {
        // 获取当前登录用户信息
        UpmpUserInfoVO user= CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt =  DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
              entity.setOprId(user.getId());
        entity.setCrtOrgId(user.getOrgCode());
        entity.setCreateTime(lastUpddt);
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);
        if (StringUtils.isBlank(entity.getBankBranchLevel())) entity.setBankBranchLevel("00");
        //检查新增操作是否需要审核，我们是保存在权限审核配置表中，新的表结构是  T_B_PRIVILEGE_CHECK
        UpmpPrivilegeCheck privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "参数管理:银联机构号管理:增加");
        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
            //需要审核，状态为草稿，审核状态为审核中
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType());
            entity.setBankBranchStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            this.baseMapper.insert(entity);
            //临时数据表数据插入-待完成
           bizTmpService.saveBizTmp(entity, user, user.getInstId(), BizOprEnum.OPR_ADD.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                        , oprMenuId, oprMenuName, entity.getBankBranchStatus(), entity.getAuditStatus(), entity.getId(), webNextUrl,null,null,null);
        } else {
            //无需审核，状态为正式，审核状态为审批通过
            entity.setBankBranchStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
            this.baseMapper.insert(entity);
            bizHisService.saveBizHisNew(entity,entity, user, user.getInstId(), BizOprEnum.OPR_ADD.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                        , oprMenuId, oprMenuName, entity.getId(),null,null,null);
        }
    }

    @Override
    @Transactional
    public void update(BankCodeInfo entity) throws RedpException {
        // 获取当前登录用户信息
        UpmpUserInfoVO user= CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt =  DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        // 修改
         entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);
        this.baseMapper.updateById(entity);
        BankCodeInfo bankCodeInfo = this.getById(String.valueOf(entity.getId()));
        BeanUtils.copyProperties(entity, bankCodeInfo);

        UpmpPrivilegeCheck privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "参数管理:银联机构号管理:修改");
        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
            bankCodeInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
            this.baseMapper.updateById(bankCodeInfo);
            //检查临时表是否有数据，如果没用则新增
            bizTmpService.saveBizTmp(bankCodeInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                    , oprMenuId, oprMenuName, bankCodeInfo.getBankBranchStatus(), bankCodeInfo.getAuditStatus(), bankCodeInfo.getId(), webNextUrl,null,null,null);
        } else {
            bankCodeInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
            this.baseMapper.updateById(bankCodeInfo);
            //历史表新增
            bizHisService.saveBizHisNew(bankCodeInfo, bankCodeInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                    , oprMenuId, oprMenuName, bankCodeInfo.getId(), null, null, null);
        }
    }
    @Override
    @Transactional
    public void cancel(String id) throws RedpException {
        // 获取当前登录用户信息
        UpmpUserInfoVO user= CommonUtils.getCurrentUser(upmpSysParamService);
        // 注销
        String lastUpddt =  DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        BankCodeInfo entity = this.getById(id);
        BankCodeInfo bankCodeInfoDB = entity;
        UpmpPrivilegeCheck privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), oprBtnNamePrefix+ BusinessContainer.AUTH_PRIVILEGE_CODE_SPLIT + PageOptFlagEnum.OPT_FLAG_CANCEL.getDesc());
        String bizOpr = BizOprEnum.OPR_CANCEL.getType();
        entity.setBankBranchStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
        entity.setLastUpdateTime(lastUpddt);
         entity.setLastOprId(user.getId());
        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
            this.baseMapper.updateById(entity);
            //检查临时表是否有数据，如果没用则新增
            bizTmpService.saveBizTmp(entity, user, user.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                        , oprMenuId, oprMenuName, entity.getBankBranchStatus(), entity.getAuditStatus(), entity.getId(), webNextUrl,null,null,null);
            } else {
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
            this.baseMapper.updateById(entity);
            //历史表新增
            bizHisService.saveBizHisNew(entity,bankCodeInfoDB, user, user.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                        , oprMenuId, oprMenuName, entity.getId(),null,null,null);

        }
    }
    @Override
    @Transactional
    public void audit(BankCodeInfo entity, String opt, String approvalRefuseReason) throws RedpException {
        // 获取当前登录用户信息
        UpmpUserInfoVO user= CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt =  DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        //获取临时表数据并转换成实体对象
        BizTmp tmp = bizTmpService.getBizTmpDetail(entity.getId());
        if (tmp != null) {
            log.error("根据id没有找到指定临时表数据！");
            throw new RedpException("根据id没有找到指定临时表数据！");
        }
        String bizdata = tmp.getBizData1() + tmp.getBizData2() + tmp.getBizData3();
        // 临时表数据
        BankCodeInfo cupsInstInfoNew = JSON.parseObject(bizdata, BankCodeInfo.class);
        // 正式表数据
        BankCodeInfo bankCodeInfo = this.getById(entity.getId());
        // 备份正式表数据
        CupsInstInfo cupsInstInfoOld = new CupsInstInfo();
        BeanUtils.copyProperties(bankCodeInfo, cupsInstInfoOld);
        //
        if (bankCodeInfo != null && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
            log.error("根据id没有找到指定数据！");
            throw new RedpException("根据id没有找到指定数据！");
        }
        if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
            // 审批通过将临时表数据更新到正式表
            BeanUtils.copyProperties(cupsInstInfoNew, bankCodeInfo);
        } else {
            bankCodeInfo.setAuditRefuseReason(approvalRefuseReason);
        }
        String bizOpr = "";
        if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(bankCodeInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                bankCodeInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                bankCodeInfo.setBankBranchStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            } else {
                bankCodeInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_ADD.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(bankCodeInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                bankCodeInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                bankCodeInfo.setBankBranchStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
            } else {
                bankCodeInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_CANCEL.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(bankCodeInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                bankCodeInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                bankCodeInfo.setBankBranchStatus(BizDataStatusEnum.STATUS_STOPED.getType());
            } else {
                bankCodeInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_STOP.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(bankCodeInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                bankCodeInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                bankCodeInfo.setBankBranchStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            } else {
                bankCodeInfo.setBankBranchStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_USE.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(bankCodeInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                bankCodeInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                bankCodeInfo.setBankBranchStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            } else {
                bankCodeInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_UPDATE.getType();
        }
        bankCodeInfo.setAuditRefuseReason(approvalRefuseReason);
        // 状态赋值完成后，入库正式表
        this.baseMapper.insert(bankCodeInfo);
        //
        if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
            //审批通过将正式表更新到历史表
            bizHisService.saveBizHisNew(bankCodeInfo,cupsInstInfoOld, user, user.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN), oprMenuId, oprMenuName, bankCodeInfo.getId(),null,null,null);
        }
        // 修改临时表的审核状态等字段
        bizTmpService.saveBizTmp(bankCodeInfo, user, user.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN), oprMenuId, oprMenuName, bankCodeInfo.getBankBranchStatus(), bankCodeInfo.getAuditStatus(), bankCodeInfo.getId(), webNextUrl,null,null,null);
    }

    @Override
    @Transactional
    public void delete(String[] ids) {
        List<String> list = Arrays.asList(ids);
        this.baseMapper.deleteBatchIds(list);
    }
}
